package com.hubiao.basics.jdk8;

import com.google.common.collect.Lists;
import lombok.Data;
import org.junit.jupiter.api.Test;

import java.util.Collections;
import java.util.Comparator;
import java.util.List;

/**
 * Description  排序
 *
 * @author hubiao
 * @since 2021-01-18 17:49
 */

public class SortDemo {

    List<User> list = Lists.newArrayList();

    @Test
    public void sort() {
        list.add( new User( "胡彪1", 42 ) );
        list.add( new User( "胡彪2", 25 ) );
        list.add( new User( "胡彪3", 65 ) );
        list.add( new User( "胡彪4", 14 ) );
        list.add( new User( "胡彪5", 8 ) );
        //jdk8 lambda排序，不带参数类型
        System.out.println( "jdk8 lambda排序，不带参数类型" );
        list.sort( (u1, u2) -> u1.getAge().compareTo( u2.getAge() ) );
        list.forEach( System.out::println );
        //jdk8 lambda排序，带参数类型
        System.out.println( "jdk8 lambda排序，带参数类型" );
        list.sort( (User u1, User u2) -> u1.getAge().compareTo( u2.getAge() ) );
        list.forEach( System.out::println );
        //jdk8 升序排序，Comparator提供的静态方法
        System.out.println( "jdk8 升序排序，Comparator提供的静态方法" );
        Collections.sort( list, Comparator.comparing( User::getAge ) );
        list.forEach( System.out::println );
        //jdk8 升序排序，Comparator提供的静态方法
        System.out.println( "jdk8 降序排序，Comparator提供的静态方法" );
        Collections.sort( list, Comparator.comparing( User::getAge ).reversed() );
        list.forEach( System.out::println );
        //jdk8 组合排序，Comparator提供的静态方法，先按年纪排序，年纪相同的按名称排序
        System.out.println( "jdk8 组合排序，Comparator提供的静态方法，先按年纪排序，年纪相同的按名称排序" );
        Collections.sort( list, Comparator.comparing( User::getAge ).thenComparing( User::getName ) );
        list.forEach( System.out::println );


    }
}

@Data
class User {

    private String name;
    private Integer age;

    public User(String name, int age) {
        this.name = name;
        this.age = age;
    }
}
